<?php
require_once 'Zend/Application/Bootstrap/ResourceBootstrapper.php';
require_once 'Zend/Application/Resource/ResourceAbstract.php';
require_once 'Cafepress/Service.php';

/**
 * This resource plugin initializes an instance of the cafepress api
 * for use throughout the application.
 * 
 * @author Michael Krotscheck
 */
class Cafepress_Application_Resource_Cafepress
	extends Zend_Application_Resource_ResourceAbstract
{
	/**
	 * Initializes the resource.
	 * 
	 * @see Zend_Application_Resource_Resource::init()
	 */
	public function init()
	{
		$options = $this->getOptions();
		$cache = $this->getCache();
		
		// Create the service instance.
		$service = new Cafepress_Service($options['apikey']);
		$service->setCache($cache);
		$service->setLogin($options['login']);
		$service->setPassword($options['password']);
		$service->setApiKey($options['apikey']);
		
		return $service;
	}

	/**
	 * Get the cache
	 *
	 * @param string
	 * @return Zend_Application_Resource_Db
	 */
	public function getCache()
	{
		$options = $this->getOptions();
		$serviceCache = null;
		
		if ( isset($options['cache']) )
		{
			$cacheName = $options['cache'];
			$bootstrap = $this->getBootstrap();
			
			if ($bootstrap instanceof Zend_Application_Bootstrap_ResourceBootstrapper && $bootstrap->hasPluginResource('CacheManager') )
			{
				$cacheManager = $bootstrap->bootstrap('CacheManager')->getResource('CacheManager');
				if (null !== $cacheManager && $cacheManager->hasCache($cacheName))
				{
					$serviceCache = $cacheManager->getCache($cacheName);
				}
			}
		}		

		return $serviceCache;
	}
}